package com.wow.app.promotion.web.open.module.action;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import com.alibaba.citrus.service.uribroker.URIBrokerService;
import com.alibaba.citrus.turbine.Context;
import com.alibaba.citrus.turbine.Navigator;
import com.alibaba.citrus.turbine.dataresolver.Param;
import com.alibaba.citrus.turbine.uribroker.uri.TurbineURIBroker;
import com.wow.app.biz.common.SessionUser;
import com.wow.app.biz.common.SessionUtil;
import com.wow.app.biz.user.UserService;
import com.wow.app.dal.dto.UserDO;

public class UserAction {
	@Resource
	UserService userService;
	@Resource
	URIBrokerService uriBrokerService;

	public void doAddUser(@Param("name") String name,
			@Param("passwd") String passwd, @Param("type") String type,
			@Param("description") String description, Navigator nav,
			Context context) {
		UserDO userDO = new UserDO();
		userDO.setName(name);
		userDO.setDescription(description);
		userDO.setPasswd(passwd);
		userDO.setType(Integer.parseInt(type));
		int userID = userService.addUser(userDO);
		context.put("uid", userID);
		nav.redirectTo("loginLink");
	}

	public void doLogin(HttpSession httpSession, @Param("name") String name,
			@Param("returnUrl") String returnUrl,
			@Param("passwd") String passwd, Navigator nav, Context context) {
		UserDO userDO = userService.getUserByName(name);
		if (userDO == null) {
			context.put("msg", "WRONG_NAME");
		} else if (!passwd.equals(userDO.getPasswd())) {
			context.put("msg", "WRONG_PASSWD");
		} else {
			context.put("msg", "LOGIN_SUCESS");
		}
		SessionUser sessionUser = new SessionUser();
		sessionUser.setLoginID(name);
		sessionUser.setUserType(String.valueOf(userDO.getType()));
		SessionUtil.addSession(httpSession, sessionUser);
		if (returnUrl != null) {
			nav.redirectToLocation(returnUrl);
		}else{
			nav.redirectTo("indexLink");
		}
		
	}

	public void doLogout(HttpSession httpSession, Navigator nav) {
		SessionUser sessionUser = SessionUtil.getSessionUser(httpSession);
		if (sessionUser != null && sessionUser.getLoginID() != null) {
			SessionUtil.removeSession(httpSession);
			TurbineURIBroker uriBroker = (TurbineURIBroker) uriBrokerService
					.getURIBroker("openModule");
			nav.redirectToLocation(uriBroker.setTarget("login.vm").render());
		}
	}
}